<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>推广员中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            padding: 15px;
            background-color: #f5f5f5;
            font-size: 14px;
        }

        .container {
            width: 100%;
            max-width: 100%;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px;
            overflow-x: auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        h1 {
            color: #333;
            font-size: 18px;
            margin: 0;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            font-size: 14px;
            color: #666;
        }

        .logout-btn {
            padding: 6px 12px;
            background-color: #6c757d;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .logout-btn:hover {
            background-color: #545b62;
        }

        .promotion-section {
            margin-bottom: 20px;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            color: white;
        }

        .promotion-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .promotion-code {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
            background: rgba(255,255,255,0.2);
            padding: 8px 12px;
            border-radius: 4px;
            display: inline-block;
        }

        .copy-btn {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s;
        }

        .copy-btn:hover {
            background-color: #45a049;
            transform: translateY(-2px);
        }

        .copy-btn:active {
            transform: translateY(0);
        }

        .promotion-link {
            margin-top: 10px;
            font-size: 12px;
            opacity: 0.8;
            word-break: break-all;
        }

        .stats-container {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .stat-item {
            padding: 12px 16px;
            border-radius: 6px;
            background-color: #f2f2f2;
            font-size: 14px;
            flex: 1;
            min-width: 120px;
            text-align: center;
        }

        .stat-total {
            background-color: #e3f2fd;
            border-left: 4px solid #2196F3;
        }

        .stat-success {
            background-color: #e8f5e9;
            border-left: 4px solid #4CAF50;
        }

        .stat-fail {
            background-color: #ffebee;
            border-left: 4px solid #f44336;
        }

        .stat-pending {
            background-color: #fff8e1;
            border-left: 4px solid #FF9800;
        }

        .refresh-btn {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .refresh-btn:hover {
            background-color: #45a049;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        th, td {
            padding: 10px 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            font-size: 13px;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
            position: sticky;
            top: 0;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

        .status-0 {
            color: #4CAF50;
            font-weight: bold;
        }

        .status-1 {
            color: #f44336;
            font-weight: bold;
        }

        .status-2 {
            color: #FF9800;
            font-weight: bold;
        }

        .message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            font-size: 14px;
            display: none;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
            display: block;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
            display: block;
        }

        .summary {
            margin-top: 15px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            font-size: 14px;
        }

        /* 手机号可复制样式 */
        .copyable {
            cursor: pointer;
            position: relative;
            display: inline-block;
            transition: all 0.2s;
        }

        .copyable:hover {
            color: #2196F3;
            text-decoration: underline;
        }

        .copyable.copied::after {
            content: '✓ 已复制';
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #4CAF50;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            white-space: nowrap;
            z-index: 10;
        }

        /* 操作按钮样式 */
        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 5px;
            transition: all 0.3s;
        }

        .action-btn:hover {
            opacity: 0.8;
        }

        .success-btn {
            background-color: #4CAF50;
            color: white;
        }

        .fail-btn {
            background-color: #f44336;
            color: white;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        @media (max-width: 768px) {
            .action-btn {
                padding: 4px 8px;
                font-size: 11px;
            }

            .action-buttons {
                flex-direction: column;
                gap: 3px;
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .container {
                padding: 10px;
                border-radius: 6px;
            }

            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            h1 {
                font-size: 16px;
            }

            .stats-container {
                width: 100%;
                justify-content: space-between;
            }

            .stat-item {
                font-size: 12px;
                padding: 8px 10px;
                min-width: 80px;
            }

            .refresh-btn {
                width: 100%;
            }

            th, td {
                padding: 8px 6px;
                font-size: 12px;
            }

            .copyable.copied::after {
                top: -18px;
                font-size: 10px;
            }
        }

        ::-webkit-scrollbar {
            height: 6px;
            width: 6px;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #ccc;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-track {
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>推广员中心</h1>
        <div class="user-info">
            <span id="currentUser">欢迎，推广员</span>
            <button id="logoutBtn" class="logout-btn">退出登录</button>
        </div>
    </div>

    <!-- 推广链接区域 -->
    <div class="promotion-section">
        <div class="promotion-title">我的推广链接</div>
        <div class="promotion-code" id="promotionCode">加载中...</div>
        <button id="copyLinkBtn" class="copy-btn">
            <i class="fas fa-copy"></i> 复制推广链接
        </button>
        <div class="promotion-link" id="promotionLink">http://yx.kukudb.cn?promotionCode=</div>
    </div>

    <div class="stats-container">
        <div class="stat-item stat-total" id="totalUsers">总用户数: 0</div>
        <div class="stat-item stat-success" id="successUsers">成功用户: 0</div>
        <div class="stat-item stat-fail" id="failUsers">失败用户: 0</div>
        <div class="stat-item stat-pending" id="pendingUsers">未处理: 0</div>
        <button id="refreshBtn" class="refresh-btn">刷新数据</button>
    </div>

    <div style="overflow-x: auto;">
        <table id="userTable">
            <thead>
            <tr>
                <th>序号</th>
                <th>手机号</th>
                <th>验证码</th>
                <th>邀请码</th>
                <th>状态</th>
                <th>注册时间</th>
                <th>验证码提交时间</th>
                <th>处理时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="userTableBody">
            <!-- 数据将通过JavaScript动态填充 -->
            </tbody>
        </table>
    </div>

    <div class="summary" id="dataSummary">
        最后更新时间: <span id="lastUpdateTime">-</span>
    </div>

    <div id="message" class="message"></div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const userTableBody = document.getElementById('userTableBody');
        const refreshBtn = document.getElementById('refreshBtn');
        const logoutBtn = document.getElementById('logoutBtn');
        const currentUserEl = document.getElementById('currentUser');
        const messageDiv = document.getElementById('message');
        const totalUsersEl = document.getElementById('totalUsers');
        const successUsersEl = document.getElementById('successUsers');
        const failUsersEl = document.getElementById('failUsers');
        const pendingUsersEl = document.getElementById('pendingUsers');
        const lastUpdateTimeEl = document.getElementById('lastUpdateTime');
        const promotionCodeEl = document.getElementById('promotionCode');
        const promotionLinkEl = document.getElementById('promotionLink');
        const copyLinkBtn = document.getElementById('copyLinkBtn');

        let refreshInterval;
        let currentUsers = [];
        let currentPromoter = null;

        // 检查登录状态
        function checkLoginStatus() {
            const userInfo = localStorage.getItem('userInfo');
            if (!userInfo) {
                window.location.href = 'login.html';
                return;
            }

            const user = JSON.parse(userInfo);
            currentUserEl.textContent = `欢迎，${user.username}`;
            
            // 直接从登录返回的数据中获取推广码
            currentPromoter = {
                username: user.username,
                promotionCode: user.promotionCode,
                role: user.role
            };
            updatePromotionInfo(currentPromoter);
        }

        // 更新推广信息
        function updatePromotionInfo(promoter) {
            if (promoter && promoter.promotionCode) {
                promotionCodeEl.textContent = promoter.promotionCode;
                const promotionLink = `http://yx.kukudb.cn?promotionCode=${promoter.promotionCode}`;
                promotionLinkEl.textContent = promotionLink;
            } else {
                promotionCodeEl.textContent = '无推广码';
                promotionLinkEl.textContent = '请联系管理员获取推广码';
                copyLinkBtn.disabled = true;
                copyLinkBtn.style.backgroundColor = '#6c757d';
                copyLinkBtn.textContent = '无法复制（无推广码）';
            }
        }

        // 初始化页面
        checkLoginStatus();
        fetchUserList();
        startAutoRefresh();

        // 手动刷新按钮
        refreshBtn.addEventListener('click', function () {
            fetchUserList();
        });

        // 退出登录
        logoutBtn.addEventListener('click', function () {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('userInfo');
                window.location.href = 'login.html';
            }
        });

        // 复制推广链接
        copyLinkBtn.addEventListener('click', function () {
            if (currentPromoter && currentPromoter.promotionCode) {
                const promotionLink = `http://yx.kukudb.cn?promotionCode=${currentPromoter.promotionCode}`;
                copyToClipboard(promotionLink, copyLinkBtn);
                showMessage('推广链接已复制到剪贴板', 'success');
            } else {
                showMessage('无法复制推广链接，请检查推广码', 'error');
            }
        });

        // 获取用户列表
        function fetchUserList() {
            fetch('/api/admin/getUserList', {
                method: 'GET'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 直接显示所有数据，不进行前端筛选
                        currentUsers = data.data;
                        renderUserTable(currentUsers);
                        updateStats(currentUsers);
                        updateLastUpdateTime();
                    } else {
                        showMessage('获取用户列表失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
        }

        // 渲染用户表格
        function renderUserTable(users) {
            userTableBody.innerHTML = '';

            // 按创建时间倒序排列，最新的在前面
            const sortedUsers = [...users].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

            sortedUsers.forEach((user, index) => {
                const row = document.createElement('tr');

                // 序号 - 按时间倒序排列
                const indexCell = document.createElement('td');
                indexCell.textContent = index + 1; // 正序序号
                row.appendChild(indexCell);

                // 手机号 - 添加复制功能
                const phoneCell = document.createElement('td');
                const phoneSpan = document.createElement('span');
                phoneSpan.textContent = user.phone;
                phoneSpan.className = 'copyable';
                phoneSpan.title = '点击复制手机号';
                phoneSpan.addEventListener('click', function(event) {
                    event.stopPropagation();
                    copyToClipboard(user.phone, phoneSpan);
                });
                phoneCell.appendChild(phoneSpan);
                row.appendChild(phoneCell);

                // 验证码
                const codeCell = document.createElement('td');
                codeCell.textContent = user.verificationCode || '-';
                row.appendChild(codeCell);

                // 邀请码
                const inviteCell = document.createElement('td');
                inviteCell.textContent = user.invitationCode || '-';
                row.appendChild(inviteCell);

                // 状态
                const statusCell = document.createElement('td');
                statusCell.className = `status-${user.isSuccess}`;

                let statusText = '';
                switch (user.isSuccess) {
                    case 0:
                        statusText = '成功';
                        break;
                    case 1:
                        statusText = '失败';
                        break;
                    case 2:
                        statusText = '未处理';
                        break;
                    default:
                        statusText = '未知';
                }

                statusCell.textContent = statusText;
                row.appendChild(statusCell);

                // 注册时间
                const timeCell = document.createElement('td');
                timeCell.textContent = formatDateTime(user.createdAt);
                row.appendChild(timeCell);

                // 验证码提交时间
                const submitTimeCell = document.createElement('td');
                submitTimeCell.textContent = user.submitTime ? formatDateTime(user.submitTime) : '-';
                row.appendChild(submitTimeCell);

                // 处理时间
                const processingTimeCell = document.createElement('td');
                processingTimeCell.textContent = user.processingTime ? formatDateTime(user.processingTime) : '-';
                row.appendChild(processingTimeCell);

                // 操作列
                const actionCell = document.createElement('td');
                const actionButtons = document.createElement('div');
                actionButtons.className = 'action-buttons';

                // 根据状态添加不同的操作按钮
                if (user.isSuccess === 2) { // 未处理状态
                    const successBtn = document.createElement('button');
                    successBtn.className = 'action-btn success-btn';
                    successBtn.textContent = '设为成功';
                    successBtn.addEventListener('click', function() {
                        updateUserStatus(user.id, user.phone, 0)
                            .then(() => fetchUserList());
                    });

                    const failBtn = document.createElement('button');
                    failBtn.className = 'action-btn fail-btn';
                    failBtn.textContent = '设为失败';
                    failBtn.addEventListener('click', function() {
                        updateUserStatus(user.id, user.phone, 1)
                            .then(() => fetchUserList());
                    });

                    actionButtons.appendChild(successBtn);
                    actionButtons.appendChild(failBtn);
                }
                else if (user.isSuccess === 1) { // 失败状态
                    const successBtn = document.createElement('button');
                    successBtn.className = 'action-btn success-btn';
                    successBtn.textContent = '设为成功';
                    successBtn.addEventListener('click', function() {
                        updateUserStatus(user.id, user.phone, 0)
                            .then(() => fetchUserList());
                    });

                    actionButtons.appendChild(successBtn);
                }

                actionCell.appendChild(actionButtons);
                row.appendChild(actionCell);

                userTableBody.appendChild(row);
            });
        }

        // 复制到剪贴板功能
        function copyToClipboard(text, element) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    showCopyFeedback(element);
                }).catch(err => {
                    useFallbackCopyMethod(text, element);
                });
            } else {
                useFallbackCopyMethod(text, element);
            }
        }

        // 传统复制方法
        function useFallbackCopyMethod(text, element) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.position = "fixed";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showCopyFeedback(element);
                } else {
                    showMessage('复制失败，请手动复制', 'error');
                }
            } catch (err) {
                showMessage('复制失败，请手动复制', 'error');
            }

            document.body.removeChild(textArea);
        }

        // 显示复制反馈
        function showCopyFeedback(element) {
            element.classList.add('copied');
            setTimeout(() => {
                element.classList.remove('copied');
            }, 2000);
        }

        // 更新统计信息
        function updateStats(users) {
            const total = users.length;
            const success = users.filter(u => u.isSuccess === 0).length;
            const fail = users.filter(u => u.isSuccess === 1).length;
            const pending = users.filter(u => u.isSuccess === 2).length;

            totalUsersEl.textContent = `总用户数: ${total}`;
            successUsersEl.textContent = `成功用户: ${success}`;
            failUsersEl.textContent = `失败用户: ${fail}`;
            pendingUsersEl.textContent = `未处理: ${pending}`;
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            lastUpdateTimeEl.textContent = now.toLocaleString();
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
        }

        // 自动刷新
        function startAutoRefresh() {
            clearInterval(refreshInterval);
            refreshInterval = setInterval(fetchUserList, 5000); // 每5秒刷新一次
        }

        // 更新用户状态（返回Promise）
        function updateUserStatus(id, phone, isSuccess) {
            const requestData = {
                id: id,
                phone: phone,
                isSuccess: isSuccess
            };

            return fetch('/api/admin/setIsSuccess', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        showMessage('状态更新成功', 'success');
                        // 立即刷新用户列表以显示最新状态
                        fetchUserList();
                        return true;
                    } else {
                        showMessage('状态更新失败: ' + data.message, 'error');
                        return Promise.reject(data.message);
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                    return Promise.reject(error);
                });
        }

        // 显示消息
        function showMessage(message, type) {
            messageDiv.textContent = message;
            messageDiv.className = 'message ' + type;

            // 3秒后自动消失
            setTimeout(() => {
                messageDiv.className = 'message';
            }, 3000);
        }
    });
</script>
</body>
</html>
